import { observable, computed, action, runInAction } from 'mobx'
import { get, post } from '@/utils/aixos'
import { getBrowserId } from '@/utils'

class UserStore {
  @observable
  info = {
    id: '',
    name: '',
    avatar: ''
  }

  @computed
  get isLogged() {
    return this.info.id && this.info.name && this.info.avatar
  }

  @action
  getInfo = async () => {
    const id = await getBrowserId()
    const res = await get('/user/info', { id })
    if (res.data) {
      runInAction(() => {
        this.info = res.data
      })
      return res.data
    } else {
      return Promise.reject()
    }
  }

  @action
  signIn = async ({ name, avatar }) => {
    const id = await getBrowserId()
    const res = await post('/user/inset', { id, name, avatar })
    if (res.code === 20000) {
      runInAction(() => {
        this.info = { id, name, avatar }
      })
    }
  }

  @action
  update = async ({ name, avatar }) => {
    const id = await getBrowserId()
    const res = await post('/user/update', { id, name, avatar })
    if (res.code === 20000) {
      runInAction(() => {
        this.info = { id, name, avatar }
      })
    }
  }
}

export default UserStore
